package com.vr.cloudpicture.api.aliyunoutpicture;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import cn.hutool.json.JSONUtil;
import com.vr.cloudpicture.api.aliyunoutpicture.model.CreateOutPaintingTaskRequest;
import com.vr.cloudpicture.api.aliyunoutpicture.model.CreateOutPaintingTaskResponse;
import com.vr.cloudpicture.api.aliyunoutpicture.model.QueryOutPaintingTaskResponse;
import com.vr.cloudpicture.exception.BusinessException;
import com.vr.cloudpicture.exception.ErrorCode;
import com.vr.cloudpicture.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 阿里云 AI API
 *
 * @author hzh
 * @date 2025/05/23
 */
@Slf4j
@Service
public class AliYunAiApi {
    /** API 密钥 */
    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    /** 创建扩图任务 URL */
    private static final String CREATE_OUT_PAINTING_TASK_URL ="https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    /** 查询扩图任务 URL */
    private static final String QUERY_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 创建扩图任务
     *
     * @param request 请求
     * @return {@code CreateOutPaintingTaskResponse }
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR,"扩图参数为空");
        // 发送请求
        HttpRequest httpRequest = HttpUtil.createPost(CREATE_OUT_PAINTING_TASK_URL)
                .header(Header.AUTHORIZATION, "Bearer" + apiKey)
                // 必须开启异步(默认)
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(request));
        try(HttpResponse httpResponse = httpRequest.execute()) {
            if (!httpResponse.isOk()) {
                log.error("请求异常:{}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR,  "AI扩图失败");
            }
            CreateOutPaintingTaskResponse response = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            String errorCode = response.getCode();
            // 成功是没有code
            if (StrUtil.isNotBlank(errorCode)) {
                log.error("AI扩图失败:errorCode:{},errorMessage:{}", errorCode,  response.getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR,  "AI扩图失败");
            }
            return response;
        }
    }

    /**
     * 查询扩图任务
     *
     * @param taskId 任务 ID
     * @return {@code QueryOutPaintingTaskResponse }
     */
    public QueryOutPaintingTaskResponse queryOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(taskId == null, ErrorCode.PARAMS_ERROR,"任务id不能为空");
        // 拼接URL
        String url = String.format(QUERY_OUT_PAINTING_TASK_URL, taskId);
        // 创建请求
        HttpRequest httpRequest = HttpUtil.createGet(url)
                .header(Header.AUTHORIZATION, "Bearer" + apiKey);
        try(HttpResponse httpResponse = httpRequest.execute()) {
            if (!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,  "获取任务失败");
            }
            return JSONUtil.toBean(httpResponse.body(), QueryOutPaintingTaskResponse.class);
        }
    }
}
